package public

import (
	"net/http"
	"gitee.com/DengAnbang/streamWeb/api/defs"
	"gitee.com/DengAnbang/streamWeb/public/session"
	"gitee.com/DengAnbang/streamWeb/public/limiter"
	"fmt"
)

var connLimiter = limiter.NewConnLimiter(1024)

type AppHandleFuncErr func(w http.ResponseWriter, r *http.Request) error


func AppHandleFunc(appHandle AppHandleFuncErr) func(http.ResponseWriter, *http.Request) {

	return func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			i := recover()
			if resultData, ok := i.(*defs.ResultData); ok {
				resultData.WriterResponse(w)
			} else if err, ok := i.(error); ok {
				data := defs.ResultData{Code: defs.InternalErr, Msg: "服务器内部错误", DebugMeg: fmt.Sprintf("%v", err)}
				data.WriterResponse(w)
			}
		}()
		//checkLimiter(w, r)
		//defer connLimiter.ReleaseConn()
		r.ParseForm()
		intercept(w, r)
		err := appHandle(w, r)
		if resultData, ok := err.(*defs.ResultData); ok {
			resultData.WriterResponse(w)
			return
		}
		if err != nil {
			data := defs.ResultData{Code: defs.InternalErr, Msg: "服务器内部错误", DebugMeg: fmt.Sprintf("%v", err)}
			data.WriterResponse(w)
		}
	}
}
func intercept(w http.ResponseWriter, r *http.Request) {
	//checkSession(w, r)
}
func checkLimiter(w http.ResponseWriter, r *http.Request) {
	if !connLimiter.GetConn() {
		panic(defs.NewResultError(defs.TooManyErr, "服务器繁忙"))
	}
}
func checkSession(w http.ResponseWriter, r *http.Request) {
	if "/user/create" == r.URL.Path {
		return
	}
	if "/user/login" == r.URL.Path {
		return
	}
	session_id := r.PostForm.Get("session_id")
	bean, ok := session.GetSession(session_id)
	if !ok || bean.IsExpire() {
		panic(defs.NewResultError(defs.SessionLoseErr, "登录失效"))
	}
}
